//
//  DisplayBabyActivityView.m
//  BabyHelper
//
//  Created by  thomas on 11-2-11.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "DisplayBabyActivityView.h"


@implementation DisplayBabyActivityView
@synthesize babyActivities;


- (void)viewDidLoad {

	self.babyActivities = [[NSMutableArray alloc]init];
	self.title = NSLocalizedString(@"Activities",@"");
    [super viewDidLoad];

	UIBarButtonItem *deleteItem = [[UIBarButtonItem alloc]
								  initWithTitle:NSLocalizedString(@"Del",@"")
								  style:UIBarButtonItemStyleBordered 
								  target:self
								  action:@selector(toggleDelete)		
								  ];
	self.navigationItem.leftBarButtonItem = deleteItem;
	[deleteItem release];

	UIBarButtonItem *addItem = [[UIBarButtonItem alloc]
								   initWithTitle:NSLocalizedString(@"Add",@"")
								   style:UIBarButtonItemStyleBordered 
								   target:self
								   action:@selector(toggleAdd)		
								   ];
	self.navigationItem.rightBarButtonItem = addItem;
	[addItem release];
	
	//self.tableView.separatorColor = [UIColor clearColor];
	
	//set background image
	self.parentViewController.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"background"]];
	self.view.backgroundColor = [UIColor clearColor];
	//set navigation background color
	self.navigationController.navigationBar.tintColor = [UIColor colorWithRed:navBarRed green:navBarGreen blue:navBarBlue alpha:navBarAlpha];
	
	[self initWithStyle:UITableViewStyleGrouped];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
	Dao *dao = [Dao getInstance];
	[self.babyActivities removeAllObjects];
	[dao QueryBabyActivityWith:@"ORDER BY TIMESTAMP DESC" records:self.babyActivities];
	[self.tableView reloadData];
}

- (void)didReceiveMemoryWarning {
	// Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
	// Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
	// Release any retained subviews of the main view.
	self.babyActivities = nil;
}


#pragma mark Table view methods

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}


// Customize the number of rows in the table view.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [self.babyActivities count];
}


// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString *CellIdentifier = @"Cell";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
    }
    
	BabyActivityEntry *entry = [self.babyActivities objectAtIndex:indexPath.row];	
	cell.textLabel.text = [NSString stringWithFormat:@"%@  %@  %@", [entry getTimeStringWithOutYear],[entry getCategoryName],[entry getAmountDetails]];
	[cell.textLabel setFont:[UIFont systemFontOfSize:16.0]];
	
	cell.detailTextLabel.text = entry.comments; 
	cell.detailTextLabel.textColor = [UIColor colorWithRed:commentsTextRed green:commentsTextGreen blue:commentsTextBlue alpha:commentsTextAlpha];
	[cell.detailTextLabel setFont:[UIFont systemFontOfSize:13.0]];
	
	NSString *result = [[NSUserDefaults standardUserDefaults] stringForKey:@"BIND_WEIBO_WITH_SINGLE_ACTIVITY"];
	if(result == nil || [result isEqualToString:@"YES"])
	{
		UIImage *image = [UIImage imageNamed:@"Sina_32x32"];
		UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
		CGRect frame = CGRectMake(0.0, 0.0, image.size.width, image.size.height);
		button.frame = frame;	// match the button's size with the image size
		[button setBackgroundImage:image forState:UIControlStateNormal];
		// set the button's target to this table view controller so we can interpret touch events and map that to a NSIndexSet
		[button addTarget:self action:@selector(accessoryButtonTapped:event:) forControlEvents:UIControlEventTouchUpInside];
		cell.accessoryView = button;
	}
	else {
		cell.accessoryView = nil;		
	}
	//cell.backgroundColor = [UIColor clearColor];
	cell.backgroundColor = [UIColor colorWithRed:cellBackgroundRed green:cellBackgroundGreen 
											blue:cellBackgroundBlue alpha:cellBackgroundAlpha];
	//cell.contentView.backgroundColor = [UIColor colorWithRed:commentsTextRed green:commentsTextGreen blue:commentsTextBlue alpha:commentsTextAlpha];
	//[entry release];	
	
	switch (entry.category) {
		case EAT_MUM_CATEGORY:
			cell.imageView.image = [UIImage imageNamed:@"mum"];
			break;
		case EAT_MILK_CATEGORY:
			cell.imageView.image = [UIImage imageNamed:@"milk_bottle"];
			break;
		case DRINK_WATER_CATEGORY:
			cell.imageView.image = [UIImage imageNamed:@"DrinkWater"];
			break;
		case PEE_CATEGORY:
			cell.imageView.image = [UIImage imageNamed:@"pee"];
			break;
		case SHIT_CATEGORY:
			cell.imageView.image =  [UIImage imageNamed:@"shit"];
			break;
		default:
			cell.imageView.image = nil;
			break;
	}
    return cell;
}

// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
		BabyActivityEntry *entry = [self.babyActivities objectAtIndex:[indexPath row]];
		Dao *dao = [Dao getInstance];
		[dao RemoveBabyActivityEntry:entry];
		[self.babyActivities removeObjectAtIndex:[indexPath row]];
        [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:YES];		
    }   
} 

- (void)dealloc {
    [super dealloc];
}

-(void)toggleAdd{
	EditBabyActivityView *childView = [[EditBabyActivityView alloc] initWithNibName:@"EditBabyActivityView" bundle:nil];
	childView.currentBabyActivityEntry = nil;
	[self.navigationController pushViewController:childView animated:YES];
	[childView release];
}

-(void)toggleDelete{
	[self.tableView setEditing:!self.tableView.editing animated:YES];
		
	if (self.tableView.editing)
		[self.navigationItem.leftBarButtonItem setTitle:NSLocalizedString(@"Done",@"")];
	else
		[self.navigationItem.leftBarButtonItem setTitle:NSLocalizedString(@"Del",@"")];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
	EditBabyActivityView *childView = [[EditBabyActivityView alloc] initWithNibName:@"EditBabyActivityView" bundle:nil];
	childView.currentBabyActivityEntry = [self.babyActivities objectAtIndex:indexPath.row];
	[self.navigationController pushViewController:childView animated:YES];
	[childView release];
}

- (void)accessoryButtonTapped:(id)sender event:(id)event
{
	NSSet *touches = [event allTouches];
	UITouch *touch = [touches anyObject];
	CGPoint currentTouchPosition = [touch locationInView:self.tableView];
	NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint: currentTouchPosition];
	if (indexPath != nil)
	{
		[self tableView: self.tableView accessoryButtonTappedForRowWithIndexPath: indexPath];
	}
}

- (void)tableView:(UITableView *)tableView accessoryButtonTappedForRowWithIndexPath:(NSIndexPath *)indexPath
{	
	
	BabyHelperAppDelegate *appDelegate = (BabyHelperAppDelegate *)[[UIApplication sharedApplication] delegate];
	UIViewController *controller = [OAuthController controllerToEnterCredentialsWithEngine: appDelegate._engine delegate: self];
	if (controller) 
	{
		UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"Alert",@"") 
														message:NSLocalizedString(@"You are not log in yet", @"")
													   delegate:nil 
											  cancelButtonTitle:@"OK"
											  otherButtonTitles:nil];
		[alert show];
		[alert release];
	}
	else {
		NSLog(@"Authenicated for %@..", appDelegate._engine.username);
		[OAuthEngine setCurrentOAuthEngine:appDelegate._engine];
		[[NSUserDefaults standardUserDefaults] setValue:[self GetReportContentWithIndexPath:indexPath] forKey:@"SavedWeiBoText"];
		ComposeViewController *composeViewController = [[ComposeViewController alloc]init];
		[self presentModalViewController:composeViewController animated:YES];
		composeViewController.messageTextField.text = [self GetReportContentWithIndexPath:indexPath];
		[composeViewController newTweet];					
	}	
/*	
	NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];  
	NSArray *languages = [defaults objectForKey:@"AppleLanguages"];  
	NSLog(@"%@", languages); 
	
	NSString *currentLanguage = [languages objectAtIndex:0];
	
	
    if ([currentLanguage isEqualToString:@"zh-Hans"]) {

    }
	else {
		// Create the item to share (in this example, a url)
		//NSURL *url = [NSURL URLWithString:@"http://getsharekit.com"];
		//SHKItem *item = [SHKItem URL:url title:@"ShareKit is Awesome!"];
		
		// Get the ShareKit action sheet
		//SHKActionSheet *actionSheet = [SHKActionSheet actionSheetForItem:item];
		
		// Display the action sheet
		//[actionSheet showFromToolbar:self.navigationController.toolbar];
	}
*/ 
}

-(NSString *)GetReportContentWithIndexPath:(NSIndexPath *)indexPath{
	
	BabyActivityEntry *entry = [self.babyActivities objectAtIndex:indexPath.row];	
	Dao *dao = [Dao getInstance];
	BabyProfile *babyProfile = [[BabyProfile alloc]init];
	[dao LoadBabyProfile:babyProfile];
	
	NSString *report = [NSString stringWithFormat:BABY_ACTIVITY_ENTRY_CONTENT_STR,
						babyProfile.Name,
						[entry getTimeStringWithOutYear],
						[entry getCategoryName],
						[entry getAmountDetails],
						entry.comments];
	[babyProfile release];
	
	return report;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
	return kBabyActivityTableViewRowHeight;
}

//set tabbar background
/*
 CGRect frame = CGRectMake(0.0, 0.0, self.view.bounds.size.width, 48);
 UIView *v = [[UIView alloc] initWithFrame:frame];
 [v setBackgroundColor:[UIColor colorWithRed:navBarRed green:navBarGreen blue:navBarBlue alpha:navBarAlpha]];
 [v setAlpha:0.5];
 [[self.parentViewController.parentViewController tabBar] addSubview:v];
 [v release];
 */

/*
 NSArray * items = [[NSArray alloc] initWithObjects: NSLocalizedString(@"Del", @""),NSLocalizedString(@"Add", @""), nil];
 UISegmentedControl * switcher = [[UISegmentedControl alloc] initWithItems: items];
 switcher.segmentedControlStyle =  UISegmentedControlStyleBar;
 [items release];
 // set the target function -- needs to check selectedIndex property
 [switcher addTarget: self action: @selector(toggleEdit:)forControlEvents: UIControlEventValueChanged];
 UIBarButtonItem * segmentBarItem = [[[UIBarButtonItem alloc] initWithCustomView: switcher] autorelease];
 self.navigationItem.rightBarButtonItem = segmentBarItem;
 [switcher release];
 */


@end

